package org.myspringframework.aop.framework;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.myspringframework.aop.AdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

//使用jdk实现的aop代理对象
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    /** aop的配置信息（增强逻辑，真实对象，切点信息） */
    private final AdvisedSupport advisedSupport;

    public JdkDynamicAopProxy(AdvisedSupport advisedSupport) {
        this.advisedSupport = advisedSupport;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        List<Object> chain = advisedSupport.getInterceptorsAndDynamicInterceptionAdvice(method, advisedSupport.getTargetSource().getTarget().getClass());
        if (chain==null||chain.size()==0){
            //没有匹配的拦截器链
            //直接反射调用原方法
            return method.invoke(advisedSupport.getTargetSource().getTarget(), args);
        }else {
            //有匹配的拦截器链
            //构造调用器
            MethodInvocation invocation = new ReflectiveMethodInvocation(advisedSupport.getTargetSource().getTarget(), method, args,  chain);
            //使用调用器递归拦截器链执行所有的methodInterceptor
            return invocation.proceed();
        }
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(advisedSupport.getTargetSource().getTarget().getClass().getClassLoader(),advisedSupport.getTargetSource().getTargetClass(),this);
    }
}
